package com.gameShare.service.user

import com.gameShare.enums.misc.ResponseCodeEnum
import com.gameShare.enums.user.UserActionEnum
import com.gameShare.exceptions.BusinessException
import com.gameShare.mappers.user.UserActionMapper
import com.gameShare.utils.StringUtils
import org.apache.ibatis.binding.BindingException
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service


@Service
open class UserActionService(private val userActionMapper: UserActionMapper) {

    private val logger = LoggerFactory.getLogger(UserActionService::class.java)

    /**
     * 更新用户行为数量
     *
     * @param userId
     * @param actionType
     * @param actionCount
     */
    fun updateUserActionCount(userId: String, actionType: Int, actionCount: Int) {
        userActionMapper.updateUserActionCount(userId, actionType, actionCount)
    }

    /**
     * 创建用户行为记录
     *
     * @param userId
     */
    fun createUserActionRecord(userId : String){
        UserActionEnum.entries.forEach {
            it -> userActionMapper.insert(userId, it.code)
        }
    }

    /**
     * 加载所有行为数量
     *
     * @param userId 用户id
     * @return
     */
    fun loadUserAllActionCount(userId: String): HashMap<String, Int> {
        // 这里是将所有的信息塞入一个hashMap用枚举的键
        try {
            return UserActionEnum.entries.associate {
                StringUtils.snakeCaseToCamelCase(it.name) to userActionMapper.selectUserActionCount(userId, it.code)
            }.toMutableMap() as HashMap<String, Int>
        } catch (e: BindingException) {
            logger.warn("未能找到用户${userId}的行为信息", e)
            throw BusinessException(ResponseCodeEnum.SERVER_ERROR.code, "未插入用户行为信息")
        }
    }
}